package com.ai.trickycards.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import com.ai.trickycards.Constant
import com.ai.trickycards.R
import com.ai.trickycards.utils.SP
import com.ai.trickycards.utils.Utils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.onCreate(savedInstanceState)
        setContent {
            Background()
            FrontImage()
        }

        val claimPointsSet = SP.getInstance(this).getStringSet(Constant.SP_KEY.CLAIM_POINTS, emptySet())!!
        val today = Utils.today()
        if (!claimPointsSet.contains(today)) {
            val mutableSet = claimPointsSet.toMutableSet()
            mutableSet.add(today)
            SP.getInstance(this@SplashActivity).edit().putStringSet(Constant.SP_KEY.CLAIM_POINTS, mutableSet).apply()

            val userInfo = appViewModel.userInfoFlow.value.copy()
            Utils.getLevelRange(userInfo.level).let {
                userInfo.score += it.levelScore
                appViewModel.changeUserInfo(userInfo)
            }
        }

        lifecycleScope.launch {
            delay(800)
            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            finish()
        }
    }

    @Preview(showSystemUi = true)
    @Composable
    private fun PreviewTest() {
        Background()
        FrontImage()
    }


    @Composable
    private fun Background() {
        Image(
            painter = painterResource(id = R.mipmap.splash_bg),
            contentDescription = null,
            contentScale = ContentScale.FillBounds,
            modifier = Modifier.fillMaxSize()
        )
    }

    @Composable
    private fun FrontImage() {
        Image(
            painter = painterResource(id = R.mipmap.splash_img),
            contentDescription = null,
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 246.dp)

        )
    }
}